package pe.com.pgn.consolidadorventas.servidorcentral.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.HibernateTemplate;

import pe.com.pgn.consolidadorventas.servidorcentral.dao.DatabaseObjectDao;
import pe.com.pgn.consolidadorventas.servidorcentral.dbo.procedures.ProcedureNoResultSet;

public class DatabaseObjectDaoImpl implements DatabaseObjectDao {

	static Logger logger = Logger.getLogger(DatabaseObjectDaoImpl.class);
	
	HibernateTemplate plantilla;
	
	public void persist(Object entity) {
		plantilla.saveOrUpdate(entity);  
	}

	public void persist(Object[] entities) {
		for(int i = 0; i < entities.length; i++) {  
	            persist(entities[i]);  
	    }
	}

	public void persist(List<?> entities) {
		if(entities!=null){
			int limite = entities.size();
			for(int i=0;i<limite;i++){
				persist(entities.get(i));
			}	
		}
	}

	public <T> List<T> find(Class<T> entityClass) {
		 List<T> entities = plantilla.loadAll(entityClass);
	     return entities;  
	}
		
	public <T> T findById(Class<T> entityClass,int id) {
		T entity = (T)plantilla.get(entityClass, id);
		return entity;
	}

	public <T> T load(Class<T> entityClass, Serializable id) {
	    T entity = (T)plantilla.load(entityClass, id);  
        return entity;  
	}

	@SuppressWarnings("unchecked")	
	public <T> List<T> findByHql(String hql) {
		 List<T> entities = (List<T>)plantilla.find(hql);  
	     return entities;  
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> findByHqlOrderBy(Class<T> entityClass, String campo,String tipoOrden) {
		String hql = "from "+entityClass.getSimpleName()+" e order by e."+campo+" "+tipoOrden;
		List<T> entities = (List<T>)plantilla.find(hql);  
		return entities;
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> findByProperty(Class<T> entityClass,String property, Object value) {
		String hql = "from "+entityClass.getSimpleName()+ " e where e."+ property + "="+value;
		List<T> entities = (List<T>)plantilla.find(hql);  
		return entities;
	}

	public void delete(Object obj) {
		plantilla.delete(obj);
	}
	
	public void callProcedureNotResultSet(String procedure){
		ProcedureNoResultSet ep = new ProcedureNoResultSet();
		String query = "{ call "+procedure+" }";
		ep.setQueryProcedure(query);
		plantilla.execute(ep);
	}

	public HibernateTemplate getPlantilla() {
		return plantilla;
	}

	public void setPlantilla(HibernateTemplate plantilla) {
		this.plantilla = plantilla;
	}

}
